window.onload = function () {
  var that
  class Box {
    constructor(str) {
      that = this
      this.tab = document.querySelector(str)
      this.span = this.tab.querySelector('.tabadd')
      this.ul = this.tab.querySelector('ul')
      this.tabscon = this.tab.querySelector('.tabscon')
      this.unit()
    }
    //给li,span,delet绑定点击事件
    unit() {
      this.li = this.tab.querySelectorAll('li')
      this.section = this.tab.querySelectorAll('section')
      this.delet = this.ul.querySelectorAll('li span:last-child')
      for (var i = 0; i < this.li.length; i++) {
        this.li[i].index = i
        this.li[i].onclick = this.toggleTab
      }
      this.span.onclick = this.add
      for (var i = 0; i < this.delet.length; i++) {
        this.delet[i].onclick = this.delete
      }
      for (var i = 0; i < this.section.length; i++) {
        this.section[i].index = i
        this.section[i].onclick = this.edit
      }
    }
    //清除样式类
    clearClass() {
      for (var i = 0; i < that.li.length; i++) {
        that.li[i].className = ''
        that.section[i].className = ''
      }
    }
    //切换功能
    toggleTab() {
      that.clearClass()
      this.className = 'liactive'
      that.section[this.index].className = 'conactive'
    }
    //增加功能
    add() {
      that.clearClass()
      var li = '<li class="liactive"><span>测试1</span><span class="iconfont icon-guanbi"></span></li>'
      that.ul.insertAdjacentHTML('beforeend', li)
      var section = '<section class="conactive">测试3</section>'
      that.tabscon.insertAdjacentHTML('beforeend', section)
      that.unit()
    }
    //删除功能
    delete(e) {
      e.stopPropagation();
      var i = this.parentNode.index
      that.ul.removeChild(that.li[i])
      that.tabscon.removeChild(that.section[i])
      that.clearClass()
      if (i != 0) {
        that.li[i - 1].className = 'liactive'
        that.section[i - 1].className = 'conactive'
      }
      else {
        that.unit()
        if (that.ul.children.length != 0) {
          that.li[i].className = 'liactive'
          that.section[i].className = 'conactive'
        }
      }
    }
    //修改功能
    edit() {
      var context = this.innerHTML
      this.innerHTML = '<input type="text" />'
      var input = this.children[0]
      input.value = context
      input.focus()
      // input.select()
      input.onblur = function () {
        this.parentNode.innerHTML = this.value
      }
      input.onkeyup = function (e) {
        if (e.keyCode === 13) {
          this.blur()
        }
      }
    }
  }
  new Box('#tab')
}